package com.design.memento;

/**
 * @author leali
 * @title: Memento
 * @projectName design
 * @description: MementoClient
 * @date 2022/1/3 20:17
 */
public class MementoClient {
    /**
     * 定义一个索引来记录当前状态所在位置
     */
    private static int index = -1;
    private static final MementoCaretaker MEMENTO_CARETAKER = new MementoCaretaker();

    public static void display(Chessman chessman) {
        System.out.println("棋子" + chessman.getLabel() + "当前位置为：" + "第" + chessman.getX() + "行" + "第" + chessman.getY() + "列。");
    }

    //下棋
    public static void play(Chessman chess) {
        MEMENTO_CARETAKER.setMementoList(chess.save());
        index++;
        System.out.println("棋子" + chess.getLabel() + "当前位置为：" + "第" + chess.getX() + "行" + "第" + chess.getY() + "列。");
    }

    //悔棋
    public static void undo(Chessman chess, int i) {
        System.out.println("******悔棋******");
        index--;
        chess.restore(MEMENTO_CARETAKER.getMemento(i - 1));
        System.out.println("棋子" + chess.getLabel() + "当前位置为：" + "第" + chess.getX() + "行" + "第" + chess.getY() + "列。");
    }

    //撤销悔棋
    public static void redo(Chessman chess, int i) {
        System.out.println("******撤销悔棋******");
        index++;
        chess.restore(MEMENTO_CARETAKER.getMemento(i + 1));
        System.out.println("棋子" + chess.getLabel() + "当前位置为：" + "第" + chess.getX() + "行" + "第" + chess.getY() + "列。");
    }

    public static void main(String[] args) {
        MementoCaretaker mementoCaretaker = new MementoCaretaker();
        Chessman chessman = new Chessman("车", 1, 1);
        display(chessman);
        mementoCaretaker.setMemento(chessman.save());
        chessman.setY(4);
        display(chessman);
        mementoCaretaker.setMemento(chessman.save());
        display(chessman);
        chessman.setX(5);
        display(chessman);
        System.out.println("******悔棋******");
        chessman.restore(mementoCaretaker.getMemento());
        display(chessman);

        System.out.println("测试多次撤销");
        Chessman chess = new Chessman("车",1,1);
        play(chess);
        chess.setY(4);
        play(chess);
        chess.setX(5);
        play(chess);
        undo(chess,index);
        undo(chess,index);
        redo(chess,index);
        redo(chess,index);
    }
}
